<template>
  <div>
    <div style="display: flex;justify-content: flex-end;margin: 5px 0">
      <el-button size="small" type="primary" style="margin-right: 70px" @click="roleDialog=true">添加角色</el-button>
    </div>
    <el-table
      :data="tableData" style="width: 100%;margin-bottom: 20px;" border>
      <el-table-column prop="roleName" label="角色名称" min-width="100" align="center"></el-table-column>
      <el-table-column prop="menuNames" label="菜单" min-width="200" align="center"></el-table-column>
      <el-table-column prop="permissionNames" label="权限" min-width="200" align="center"></el-table-column>

      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" type="primary" @click="handleMenu(scope.row)">菜单权限</el-button>
            <el-button size="mini" type="info" @click="handleComponent(scope.row)">组件</el-button>
            <el-button size="mini" type="warning" @click="handlePer(scope.row)">授权</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="roleName" :visible.sync="dialog" width="600px" @close="closeDialog">
      <el-form :model="Form" ref="Form">
        <el-tree ref="tree" :data="menu" show-checkbox node-key="id" :props="defaultProps" accordion></el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-right: 50px">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增" :visible.sync="roleDialog" width="500px" @close="closeRoleDialog">
      <el-form :model="roleForm" ref="roleForm" label-width="80px">
        <el-form-item prop="roleName" label="角色名" :rules="[{ required: true, message: '请输入角色名', trigger: 'blur'}]">
          <el-input v-model="roleForm.roleName" placeholder="角色名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-right: 50px">
        <el-button @click="closeRoleDialog">取 消</el-button>
        <el-button type="primary" @click="submitRoleForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="editDialog" width="500px" @close="closeRenameDialog">
      <el-form :model="rename" ref="rename" label-width="80px">
        <el-form-item prop="roleName" label="角色名" :rules="[{ required: true, message: '请输入角色名', trigger: 'blur'}]">
          <el-input v-model="rename.roleName" placeholder="角色名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-right: 50px">
        <el-button @click="closeRenameDialog">取消</el-button>
        <el-button type="danger" @click="deleteRole">删除</el-button>
        <el-button type="primary" @click="submitRename">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="roleName" width="700px" :visible.sync="PerDialog" @close="closePermissionDialog">
      <div style="display: flex;justify-content: center;width: 100%">
        <el-transfer filterable filter-placeholder="请输入授权名检索" :titles="['全部','已拥有']"
                     v-model="rolePermission" :data="permission" :props="{ key:'id',label:'description' }">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePermissionDialog">取 消</el-button>
        <el-button type="primary" @click="submitPer">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="roleName" width="700px" :visible.sync="ComponentDialog" @close="closeComponentDialog">
      <div style="display: flex;justify-content: center;width: 100%">
        <el-transfer filterable filter-placeholder="请输入组件名检索" :titles="['全部','已拥有']"
                     v-model="roleComponent" :data="components" :props="{ key:'id',label:'remark' }">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeComponentDialog">取 消</el-button>
        <el-button type="primary" @click="submitComponent">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "RoleManager",
  data() {
    return {
      tableData: [],

      dialog: false,
      roleDialog: false,
      PerDialog: false,
      editDialog: false,
      ComponentDialog: false,

      defaultProps: {label: 'menuName', children: 'childMenu'},
      menu: [],
      roleName: '',
      Form: {
        menuId: [],
        roleId: '',
      },
      roleForm: {
        roleName: ''
      },
      rename: {
        id: '',
        roleName: ''
      },
      permission: [],
      roleId: '',
      rolePermission: [],

      components: [],
      roleComponent: []
    }
  }, methods: {
    submit() {
      this.Form.menuId = this.$refs.tree.getCheckedKeys();
      let formData = new FormData();
      formData.append('roleId', this.Form.roleId);
      formData.append('menuId', this.Form.menuId);
      this.$axios.post('/role/setRoleMenu', formData).then(res => {
        if (res.code === 200) {
          this.$message({type: 'success', duration: 1000, message: '修改成功!'});
          this.getData();
          this.closeDialog();
        }
      })
    },
    submitRoleForm() {
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          this.$axios.post('/role/addRole', this.$qs.stringify(this.roleForm)).then(res => {
            if (res.code === 200) {
              this.$message({type: 'success', duration: 1000, message: '修改成功!'});
              this.getData();
              this.closeRoleDialog();
            }
          })
        }
      });
    },
    submitPer() {
      let formData = new FormData();
      formData.append('roleId', this.roleId);
      formData.append('permissionIds', this.rolePermission);
      this.$axios.post('/role/editPermission', formData).then(res => {
        if (res.code === 200) {
          this.$message({type: 'success', duration: 1000, message: '修改成功!'});
          this.getData();
          this.closePermissionDialog();
        }
      });
    },
    submitComponent() {
      let formData = new FormData();
      formData.append("roleId", this.roleId);
      formData.append("componentIds", this.roleComponent);
      this.$axios.post('/component/editRoleComponents', formData).then(res => {
        if (res.code === 200) {
          this.$message({type: 'success', duration: 1000, message: '修改成功!'});
          this.getData();
          this.closeComponentDialog();
        }
      });
    },
    submitRename() {
      this.$refs['rename'].validate(valid => {
        if (valid) {
          this.$axios.post('/role/rename', this.$qs.stringify(this.rename)).then(res => {
            if (res.code === 200) {
              this.$message({type: 'success', duration: 1000, message: '修改成功!'});
              this.getData();
              this.closeRenameDialog();
            }
          })
        }
      });
    },
    deleteRole() {
      this.$confirm('确认删除?').then(() => {
        this.$axios.post('/role/deleteRole', this.$qs.stringify({id: this.rename.id})).then(res => {
          if (res.code === 200) {
            this.closeRenameDialog();
            this.$message({type: 'success', duration: 1000, message: '删除成功!'});
            this.getData();
          }
        });
      }).catch(() => {
      });
    },
    handleMenu(row) {
      this.dialog = true;
      this.$axios.post('/role/findMenuByRoleId', this.$qs.stringify({roleId: row.id})).then(res => {
        if (res.code === 200) {
          this.roleName = row.roleName;
          this.Form.roleId = row.id;
          this.$refs.tree.setCheckedKeys(res.data);
        }
      });
    },
    handleComponent(row) {
      this.roleName = row.roleName;
      this.roleId = row.id;

      this.$axios.post('/component/findComponentsRoleId', this.$qs.stringify({roleId: row.id})).then(res => {
        if (res.code === 200) {
          this.ComponentDialog = true;
          for (let item of res.data.data) {
            this.roleComponent.push(item.id);
          }
        }
      });
    },
    handlePer(row) {
      this.PerDialog = true;
      this.roleName = row.roleName;
      this.roleId = row.id;
      this.$axios.post('/role/findPermissionByRoleId', this.$qs.stringify({roleId: row.id})).then(res => {
        if (res.code === 200) {
          for (let item of res.data) {
            this.rolePermission.push(item.id);
          }
        }
      });
    },
    handleEdit(row) {
      this.editDialog = true;
      this.rename = {id: row.id, roleName: row.roleName}
    },
    closeDialog() {
      this.dialog = false;
      this.roleName = '';
      this.Form = {menuId: '', roleId: ''};
      this.$refs['Form'].resetFields();//清除验证
    },
    closeRoleDialog() {
      this.roleDialog = false;
      this.roleForm = {roleName: ''};
      this.$refs['roleForm'].resetFields();
    },
    closePermissionDialog() {
      this.PerDialog = false;
      this.roleName = '';
      this.roleId = '';
      this.rolePermission = [];
    },
    closeRenameDialog() {
      this.editDialog = false;
      this.rename = {id: '', roleName: ''};
      this.$refs['rename'].resetFields();
    },
    closeComponentDialog() {
      this.ComponentDialog = false;
      this.roleName = '';
      this.roleId = '';
      this.roleComponent = [];
    },
    getMenu() {
      this.$axios.post('/menu/getAllMenu').then(res => {
        if (res.code === 200) {
          this.menu = res.data;
        }
      });
    },
    getData() {
      this.$axios.post('/role/getAllRole').then(res => {
        if (res.code === 200) {
          for (let item of res.data) {
            let menuNames = '';
            let permissionNames = '';
            if (item.menuList) {
              for (let itemM of item.menuList) {
                menuNames += itemM.menuName + '、';
              }
            }
            if (item.permissions) {
              for (let itemP of item.permissions) {
                permissionNames += itemP.description + '、';
              }
            }
            item.menuNames = menuNames.substring(0, menuNames.length - 1);
            item.permissionNames = permissionNames.substring(0, permissionNames.length - 1);
          }
          this.tableData = res.data;
        }
      });
    },
    getPermission() {
      this.$axios.post('/permission/findAllPermission').then(res => {
        if (res.code === 200) {
          this.permission = res.data;
        }
      });
    },
    getComponents() {
      this.$axios.post('/component/getAll').then(res => {
        if (res.code === 200) {
          this.components = res.data.data;
        }
      });
    }
  }, created() {
    this.getData();
    this.getMenu();
    this.getPermission();
    this.getComponents();
  }
}
</script>

<style scoped>

</style>
